package com.zmx.patients.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.zmx.patients.BaseActivity;
import com.zmx.patients.R;
import com.zmx.patients.adapter.BaiduAddressAdapter;
import com.zmx.patients.pojo.MyPoiInfo;
import com.zmx.patients.view.util.PoiOverlay;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
*时间：2020/5/15 14:06
*功能：社区医院
*/
public class CommunityActivity extends BaseActivity implements View.OnClickListener, BaiduMap.OnMapLoadedCallback {

    BaiduMap baiduMap;
    PoiSearch poiSearch;
    int radius = 9000;//检索半径
    int pageIndex = 0;//页码
    int pageCapacity = 20;//每页条数
    Activity activity;
    @BindView(R.id.mapv_poi)
    MapView mapv_poi;
    @BindView(R.id.listView)
    ListView listView;

    //定位当前位置相关
    private LocationClient mLocationClient;
    double lat;//维度
    double lng;//经度
    MapStatus ms;

    private int numType;//判断显示那种图标

    private BaiduAddressAdapter addressAdapter;//地址适配器
    List<PoiInfo> poiInfos;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_community;
    }

    @Override
    protected void initViews() {

        setToolbar(R.id.tool_bar);

        poiSearch = PoiSearch.newInstance();//创建POI检索实例
        activity = CommunityActivity.this;
        List<String> permissionList = new ArrayList<>();
        //获取数据信息
        if (ContextCompat.checkSelfPermission(CommunityActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(CommunityActivity.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(CommunityActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(activity, permissions, 1);
        } else {

            initData();

        }
    }

    @Override
    public void onMapLoaded() {
        ms = new MapStatus.Builder().zoom(6).build();
        baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
    }

    private void initData() {
        poiSearch.setOnGetPoiSearchResultListener(poiSearchResultListener);
        //首先定位获取当前经纬度定位
        initLocation();
        requestLocation();

    }


    //创建POI检索监听
    OnGetPoiSearchResultListener poiSearchResultListener = new OnGetPoiSearchResultListener() {
        @Override
        public void onGetPoiResult(PoiResult poiResult) {

            // 获取POI检索结果
            if (poiResult == null || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                Toast.makeText(CommunityActivity.this, "未找到结果", Toast.LENGTH_LONG).show();
                //只把当前的添加进去
                if (baiduMap != null) {

                    baiduMap.clear();

                    PoiOverlay ov = new MyPoiOverlay(baiduMap);
                    baiduMap.setOnMarkerClickListener(ov);
                    //把当前定位点添加到集合的最后一个
                    PoiInfo poiInfo = new PoiInfo();
                    poiInfo.setLocation(new LatLng(lat, lng));
                    poiInfo.setName("这是坐标点");
//                poiResult.getAllPoi().set(poiInfos.size()+1,poiInfo);
                    PoiResult poiResult1 = new PoiResult();
                    List<PoiInfo> poiInfoList = new ArrayList<>();
                    poiInfoList.add(poiInfo);
                    poiResult1.setPoiInfo(poiInfoList);
                    //在这里处理显示那种图标的问题
                    ov.setData(poiResult1, numType);
                    //添加PoiOverlay到地图中
                    ov.addToMap();
                    ov.zoomToSpan();

                }


                return;
            }
            if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {
                /**
                 * PoiInfo中包含了经纬度、城市、地址信息、poi名称、uid、邮编、电话等等信息；
                 有了这些，你是不是可以可以在这里画一个自定义的图层了，然后添加点击事件，做一些操作了呢
                 */
                poiInfos = poiResult.getAllPoi();//poi列表

                //只把当前的添加进去
                if (baiduMap != null) {
                    baiduMap.clear();
                }
                //传递进来的经纬度，这里使用的是定位的
                LatLng llText = new LatLng(lat, lng);
                baiduMap = mapv_poi.getMap();
                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.zoomBy(4);
                baiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(llText));//设置定位的位置在屏幕的中间位置
                baiduMap.animateMapStatus(mapStatusUpdate);


//                mapv_poi.showScaleControl(false);
//                mapv_poi.showZoomControls(false);
//                mapv_poi.setNestedScrollingEnabled(false);

//                UiSettings settings = baiduMap.getUiSettings();
//                settings.setAllGesturesEnabled(false);//关闭一切手势操作

                //构建Marker图标，设置位置圆点
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.mipmap.dingwei);
                //构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions()
                        .position(llText)
                        .icon(bitmap);
                baiduMap.addOverlay(option);

                //创建PoiOverlay
                PoiOverlay overlay = new MyPoiOverlay(baiduMap);
                //设置overlay可以处理标注点击事件
                baiduMap.setOnMarkerClickListener(overlay);
                //设置PoiOverlay数据

                //把当前定位点添加到集合的最后一个
                PoiInfo poiInfo = new PoiInfo();
                poiInfo.setLocation(new LatLng(lat, lng));
                poiInfo.setName("这是坐标点");
//                poiResult.getAllPoi().set(poiInfos.size()+1,poiInfo);
                PoiResult poiResult1 = new PoiResult();
                poiInfos.add(poiInfo);
                poiResult1.setPoiInfo(poiInfos);

                //在这里处理显示那种图标的问题
                overlay.setData(poiResult1, numType);

                //添加PoiOverlay到地图中

                overlay.addToMap();
                overlay.zoomToSpan();

                //地图列表数据
                //去除最后一条数据
                if (poiInfos.size()>1) {
                    poiInfos.remove(poiInfos.size() - 1);
                }

                List<MyPoiInfo> ls = new ArrayList<>();
                for (int i=0;i<poiInfos.size();i++){

                    MyPoiInfo mp = new MyPoiInfo();
                    mp.setName(poiInfos.get(i).getName());
                    mp.setAddress(poiInfos.get(i).getAddress());
                    mp.setPf_jing(poiInfos.get(i).getLocation().longitude);
                    mp.setPf_wei(poiInfos.get(i).getLocation().latitude);
                    mp.setUser_jing(lng);
                    mp.setUser_wei(lat);
                    mp.setDistance(poiInfos.get(i).getDistance());
                    ls.add(mp);

                }

                addressAdapter = new BaiduAddressAdapter(activity,ls);
                listView.setAdapter(addressAdapter);


                return;
            }
        }

        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {//获取某个Poi详细信息

            //获取Place详情页检索结果
        }

        @Override
        public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {//查询室内poi检索结果回调

        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mapv_poi.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mapv_poi.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mapv_poi.onPause();
    }

    //定位方法
    private void initLocation() {

        mLocationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 高精度
        option.setAddrType("all");
        option.setCoorType("bd09ll");
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);
        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                StringBuilder currentPosition = new StringBuilder();
                currentPosition.append("维度：").append(bdLocation.getLatitude()).append("\n");
                currentPosition.append("经度：").append(bdLocation.getLongitude()).append("\n");
                currentPosition.append("国家：").append(bdLocation.getCountry()).append("\n");
                currentPosition.append("省：").append(bdLocation.getProvince()).append("\n");
                currentPosition.append("市：").append(bdLocation.getCity()).append("\n");
                currentPosition.append("区：").append(bdLocation.getDistrict()).append("\n");
                currentPosition.append("街道：").append(bdLocation.getStreet()).append("\n");
                currentPosition.append("定位方式：");
                Log.e("tag", "当前的定位方式=" + bdLocation.getLocType());
                if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
                    currentPosition.append("GPS");
                } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                    currentPosition.append("网络");
                }
                Log.e("address", "定位数据：=" + currentPosition);
                lat = bdLocation.getLatitude();
                lng = bdLocation.getLongitude();


                sendPoiSearch();
            }
        });


    }

    /*地图定位相关*/
    private void requestLocation() {
        mLocationClient.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public void sendPoiSearch() {

        numType = 2;
        poiSearch.searchNearby(new PoiNearbySearchOption()
                .sortType(PoiSortType.distance_from_near_to_far)
//                        .sortType(PoiSortType.comprehensive)
                .keyword("医院")
                .radius(radius)
                .pageCapacity(pageCapacity)
                .pageNum(pageIndex)
                .location(new LatLng(lat, lng)));

    }

    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override

        public boolean onPoiClick(int index) {
            super.onPoiClick(index);
            return true;
        }
    }


    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    public double getDistance(double longitude1, double latitude1,
                              double longitude2, double latitude2){

        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }


}
